#!/usr/bin/env python3

# convert videos in the mobile from m3u8 to mp4

import os
import glob
import sys

FFMPEG="ffmpeg"

def m3u8_to_mp4(m3u8):
  fname = os.path.basename(m3u8)
  video_dir = os.path.join(m3u8_dir, ".%s.d" % fname)
  local_m3u8 = os.path.join(video_dir, "1.m3u8")
  mp4 = m3u8.replace('.m3u8', '.mp4')
  with open(m3u8, 'r') as f:
     fw = open(local_m3u8, 'w')
     for line in f:
       if '/storage' in line:
         s_idx = line.find('/storage')
         e_idx = line.rfind('/')
         wline = line[0:s_idx] + line[e_idx+1:]
       else:
         wline = line
       fw.write(wline)
     fw.close()

  cmd = "%s -allowed_extensions ALL -i '%s' -c copy -v 0 '%s'" % (FFMPEG, local_m3u8, mp4)
  print(cmd)
  os.system(cmd)


if __name__ == "__main__":
  if len(sys.argv) < 2:
    print("Usage: %s m3u8_dir [ffmpeg_path]" % sys.argv[0])
    sys.exit()

m3u8_dir = sys.argv[1]
if len(sys.argv) > 2:
  FFMPEG = sys.argv[2]

files = glob.glob(os.path.join(m3u8_dir, "*.m3u8"))
for m3u8 in files:
  m3u8_to_mp4(m3u8)


